import { setToken, clearToken, getToken } from '../utils/tokenUtils.js';
import { setUserInfo, clearUserInfo, getUserInfo } from '../utils/userInfoUtils';
import {login, getUserInfo as getUserInfoAPI, register } from '../api/user.js'
const state = {
	token: getToken(),
	userInfo: getUserInfo(),
}

const mutations = {
	setUserInfo(state, userInfo) {
		state.userInfo = userInfo;
		setUserInfo(userInfo)
	},
	setToken(state, token) {
		state.token = token;
		setToken(token)
	},
	setType(state, type) {
		state.type = type;
	}
}

const actions = {
	async handleLogin({dispatch,commit}, userForm) {
		return new Promise((resolve, reject)=> {
			login(userForm).then(res=>{
				if(res.code==200) {
					const {token} = res.data;
					console.log(token, '登录成功');
					commit("setToken", token)
					dispatch("handleGetUserInfo")
					resolve("login:ok")
				} else {
					reject(res.message)
				}
			})
		})
	},
	async handleRegister({commit}, userForm) {
		return new Promise((resolve, reject)=> {
			register(userForm).then(res=>{
				if(res.code==200) {
					resolve("login:ok")
				} else {
					reject(res.message)
				}
			})
		})
	},
	handleGetUserInfo({commit}) {
		getUserInfoAPI().then(res=>{
			if(res.code==200) {
				const {userInfo} = res.data;
				commit("setUserInfo", userInfo)
			}
		})
	}, 
	async handleLogout({commit}) {
		clearToken()
		clearUserInfo()
		commit("setToken", "")
		commit("setUserInfo", {})
	}
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
};